/*
VR按钮组件
用于进入和退出VR模式，专为钓鱼游戏设计
*/

import { PicoVRConfig } from './PicoVRConfig.js';

class VRButton {
  static createButton(renderer, options = {}) {
    const button = document.createElement('button');
    
    const defaultOptions = {
      textEnterVR: '🎣 进入VR钓鱼',
      textExitVR: '🚪 退出VR',
      textVRNotFound: '⚠️ VR不支持',
      backgroundColor: 'rgba(46, 139, 87, 0.9)',
      hoverColor: 'rgba(34, 119, 72, 1)',
      textColor: '#ffffff',
      fontSize: '16px',
      fontFamily: 'Microsoft YaHei, Arial, sans-serif'
    };
    
    const config = { ...defaultOptions, ...options };
    
    // 应用样式
    function applyStyles() {
      button.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 16px 24px;
        background: ${config.backgroundColor};
        color: ${config.textColor};
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 12px;
        font: bold ${config.fontSize} ${config.fontFamily};
        cursor: pointer;
        z-index: 999;
        min-width: 140px;
        text-align: center;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        transition: all 0.3s ease;
        user-select: none;
        outline: none;
      `;
    }
    
    // 设置悬停效果
    function setupHoverEffects() {
      button.addEventListener('mouseenter', () => {
        button.style.background = config.hoverColor;
        button.style.transform = 'translateY(-2px)';
        button.style.boxShadow = '0 6px 16px rgba(0, 0, 0, 0.4)';
      });
      
      button.addEventListener('mouseleave', () => {
        button.style.background = config.backgroundColor;
        button.style.transform = 'translateY(0)';
        button.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
      });
    }
    
    // 更新按钮状态
    function updateButton() {
      if (!renderer.xr.isPresenting) {
        // 非VR模式
        button.textContent = config.textEnterVR;
        button.disabled = false;
        button.style.opacity = '1';
      } else {
        // VR模式
        button.textContent = config.textExitVR;
        button.disabled = false;
        button.style.opacity = '1';
      }
    }
    
    // 显示不支持VR的状态
    function showNotSupported() {
      button.textContent = config.textVRNotFound;
      button.disabled = true;
      button.style.opacity = '0.6';
      button.style.cursor = 'not-allowed';
      button.style.background = 'rgba(139, 69, 19, 0.9)';
    }
    
    // 创建提示信息
    function createTooltip(message) {
      const tooltip = document.createElement('div');
      tooltip.style.cssText = `
        position: fixed;
        bottom: 90px;
        right: 20px;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 12px 16px;
        border-radius: 8px;
        font: 14px ${config.fontFamily};
        z-index: 1000;
        max-width: 280px;
        line-height: 1.4;
        opacity: 0;
        transition: opacity 0.3s ease;
      `;
      tooltip.textContent = message;
      document.body.appendChild(tooltip);
      
      setTimeout(() => {
        tooltip.style.opacity = '1';
      }, 10);
      
      setTimeout(() => {
        tooltip.style.opacity = '0';
        setTimeout(() => {
          if (tooltip.parentNode) {
            tooltip.parentNode.removeChild(tooltip);
          }
        }, 300);
      }, 3000);
    }
    
    // 处理VR按钮点击
    async function handleVRButtonClick() {
      try {
        if (renderer.xr.isPresenting) {
          // 退出VR
          await renderer.xr.getSession().end();
        } else {
          // 进入VR
          createTooltip('正在启动VR钓鱼模式...');
          
          // 应用Pico VR配置
          await PicoVRConfig.configurePicoSession(renderer);
          
          // 创建VR会话
          const session = await PicoVRConfig.createFishingSession();
          await renderer.xr.setSession(session);
          
          createTooltip('🎣 VR钓鱼模式已启动！');
        }
      } catch (error) {
        console.error('VR操作失败:', error);
        createTooltip('VR启动失败，请检查设备连接');
      }
    }
    
    // 初始化按钮
    async function initButton() {
      applyStyles();
      setupHoverEffects();
      
      if (navigator.xr) {
        try {
          const supported = await navigator.xr.isSessionSupported('immersive-vr');
          if (supported) {
            updateButton();
            button.addEventListener('click', handleVRButtonClick);
            
            // 监听VR会话状态变化
            renderer.xr.addEventListener('sessionstart', updateButton);
            renderer.xr.addEventListener('sessionend', updateButton);
            
            // 检测设备类型并显示提示
            const isPico = await PicoVRConfig.detectPicoDevice();
            if (isPico) {
              createTooltip('检测到Pico VR设备，钓鱼体验已优化');
            } else {
              createTooltip('使用标准VR模式，建议使用Pico设备');
            }
          } else {
            showNotSupported();
            createTooltip('当前浏览器不支持WebXR，请使用支持VR的浏览器');
          }
        } catch (error) {
          showNotSupported();
          createTooltip('VR功能检测失败，请确保HTTPS环境');
        }
      } else {
        showNotSupported();
        createTooltip('需要HTTPS环境和支持WebXR的浏览器');
      }
    }
    
    // 异步初始化
    initButton();
    
    return button;
  }
}

export { VRButton }; 